package com.medaxis.hpams.sso.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.medaxis.hpams.dto.global.BaseResponse;
import com.medaxis.hpams.dto.global.ErrorException;
import com.medaxis.hpams.dto.global.SuccessResponse;
import com.medaxis.hpams.sso.domain.dto.PageDomain;
import com.medaxis.hpams.sso.domain.dto.TableDataInfo;
import com.medaxis.hpams.sso.domain.dto.TableSupport;
import com.medaxis.hpams.sso.utils.DateUtils;
import com.medaxis.hpams.sso.utils.SqlUtil;
import com.medaxis.hpams.sso.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    public BaseController() {
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                this.setValue(DateUtils.parseDate(text));
            }
        });
    }

    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }

    }

    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.OK.value());
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal((new PageInfo(list)).getTotal());
        return rspData;
    }

    protected BaseResponse toBaseResponse(int rows) throws RuntimeException{
        if (rows>0){
            return   SuccessResponse.success("操作成功");
        }
        throw  new ErrorException("操作失败");

    }
}